package org.ft.dao;

import org.ft.eneity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Chen Tianzhong in 2022/3/9
 */
public class UserDao {

    private static final Logger log = LoggerFactory.getLogger(UserDao.class);

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public SysUser findByUsername(String username){
        String sql="SELECT * FROM PUBLIC.SYS_USER WHERE USERNAME = ?";
        SysUser user = null;
        try {
            user = (SysUser) jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper(SysUser.class));
//        }catch (EmptyResultDataAccessException e){
//            //log.error("sql:"+sql+" , param:"+username+"; 查询结果为Empty");
//            //log.error(e.getLocalizedMessage(),e);
//            return null;
//        }catch (IncorrectResultSizeDataAccessException e){
//            //log.error("sql:"+sql+" , param:"+username+"; 查询多个相同username的对象");
//            //log.error(e.getLocalizedMessage(),e);
//            return null;
        }catch (Exception e){
            user = null;
        }
        return user;
    }

    public Map findMapByUsername(String username){
        String sql="SELECT * FROM PUBLIC.SYS_USER WHERE USERNAME = ?";
        Map<String, Object> map = new HashMap<>();
        try {
            map = jdbcTemplate.queryForMap(sql, new Object[]{username});
        }catch (EmptyResultDataAccessException e){
            log.info("sql:"+sql+" , param:"+username+"; 查询结果为Empty");
            //log.error(e.getLocalizedMessage(),e);
            return null;
        }catch (IncorrectResultSizeDataAccessException e){
            log.info("sql:"+sql+" , param:"+username+"; 查询多个相同user的对象");
            //log.error(e.getLocalizedMessage(),e);
            return null;
        }
        return map;
    }
}
